package com.example.ocupacionsuperficie;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;

public class MainActivity extends Activity implements View.OnClickListener {

	private Drawable[][] defaultDrawable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		TableLayout tl = (TableLayout) findViewById(R.id.tablelayout);
		Context context = getApplicationContext();

		defaultDrawable = new Drawable[10][5];

		for (int i = 0; i < 10; i++) {
			/* Create a new row to be added. */
			TableRow tr = new TableRow(context);
			tr.setId(i);
			tr.setLayoutParams(new TableRow.LayoutParams(
					TableRow.LayoutParams.WRAP_CONTENT,
					TableRow.LayoutParams.WRAP_CONTENT));
			Button b = null;

			for (int j = 0; j < 5; j++) {
				/* Create a Button to be the row-content. */
				b = new Button(context);
				b.setId(i + j);
				b.setText(i + "-" + j);
				b.setOnClickListener(this);
				b.setLayoutParams(new TableRow.LayoutParams(
						TableRow.LayoutParams.WRAP_CONTENT,
						TableRow.LayoutParams.WRAP_CONTENT));
				/* Add Button to row. */
				tr.addView(b);
			}
			/* Add row to TableLayout. */
			tl.addView(tr, new TableLayout.LayoutParams(
					TableLayout.LayoutParams.MATCH_PARENT,
					TableLayout.LayoutParams.WRAP_CONTENT));
		}

	}

	@Override
	public void onClick(View view) {
		if (!(view instanceof Button)) {
			return;
		}
		Button b = (Button) view;
		TableRow tr = (TableRow) b.getParent();
		int i = tr.getId(), j = b.getId() - i;
		Drawable defDrawable = defaultDrawable[i][j];

		if (defDrawable == null) {
			defaultDrawable[i][j] = b.getBackground();
			b.setBackgroundColor(getResources().getColor(
					android.R.color.holo_orange_light));
			// defaultDrawable[view.getId()] = b.getBackground();
		} else {
			// b.setBackgroundColor(getResources().getColor(
			// android.R.color.darker_gray));
			b.setBackground(defDrawable);
			defaultDrawable[i][j] = null;
		}
	}
}
